package com.ztk.threadbasic.excel.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * excel中单元格的合并策略
 */
public class CustomMergeStrategy implements CellWriteHandler {

    private Object tempCellValuePrev = null;

    // 第一列中，字体需要加粗的行数
    private final List<Integer> first_column_bold = Arrays.asList(6, 7, 8, 9);


    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            // 校验：当前是表头，则不处理
            return;
        }

        // 校验：如果当前是第一行，则不处理
        if (Objects.isNull(relativeRowIndex) || relativeRowIndex == 0) {
            return;
        }

        // 获取excel中当前sheet对象
        Sheet sheet = cell.getSheet();

        if (cell.getColumnIndex() != 0) {
            return;
        }
        // 获取当前行数
        int rowIndexCurrent = cell.getRowIndex();

        if (first_column_bold.contains(rowIndexCurrent)) {
            Workbook workbook = sheet.getWorkbook();
            CellStyle cellStyle = cell.getCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
        }

        // 获取上一行的行数
        int rowIndexPrev = rowIndexCurrent - 1;
        // 获取上一行的行数据对象
        Row rowPrev = sheet.getRow(rowIndexPrev);
        Object cellValuePrev = null;
        Cell cellPrev = null;
        // 获取当前单元格
        Object cellValueCurrent = cell.getCellType() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();

        // 因为获取上一行数据时，无法获取，sheet中不包含上一行数据，导致rowPrev可能为空
        // 所以，每次都记录下上一次的数据，如果获取的rowPrev是空的，则通过记录下的上一次数据进行比较
        if (Objects.isNull(rowPrev)) {
            cellValuePrev = tempCellValuePrev;
        } else {
            // 获取上一行所有的列数据对象
            cellPrev = rowPrev.getCell(cell.getColumnIndex());
            // 获取上一单元格
            cellValuePrev = cellPrev.getCellType() == CellType.STRING ? cellPrev.getStringCellValue() : cellPrev.getNumericCellValue();
        }
        tempCellValuePrev = cellValueCurrent;
        if (!cellValueCurrent.equals(cellValuePrev)) {
            // 当前单元格与上一单元格不相等，则结束
            return;
        }

        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();

        boolean merged = false;

        for (int i = 0; i < mergedRegions.size(); i++) {
            CellRangeAddress cellRangeAddress = mergedRegions.get(i);
            if (cellRangeAddress.isInRange(rowIndexPrev, cell.getColumnIndex())) {
                sheet.removeMergedRegion(i);
                cellRangeAddress.setLastRow(rowIndexCurrent);
                sheet.addMergedRegion(cellRangeAddress);
                merged = true;
                break;
            }
        }

        if (!merged) {
            CellRangeAddress cellAddresses = new CellRangeAddress(rowIndexPrev, rowIndexCurrent, cell.getColumnIndex(), cell.getColumnIndex());
            sheet.addMergedRegion(cellAddresses);
        }
    }
}
